package com.easy.query.solon.web.controller;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.core.annotation.EasyQueryTrack;
import com.easy.query.solon.annotation.Db;
import com.easy.query.solon.web.domain.TestUpdateEntity;
import com.easy.query.solon.web.dto.TestUpdate2Rquest;
import org.dromara.hutool.core.bean.BeanUtil;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.validation.annotation.Validated;

/**
 * create time 2023/8/21 21:57
 * 文件说明
 *
 * @author xuejiaming
 */
@Controller
@Mapping("/testUpdate")
public class TestUpdateController {

    @Db
    private EasyQuery easyQuery;
    @Mapping(value = "/init",method = MethodType.GET)
    public String testUpdate1(){
        TestUpdateEntity testUpdateEntity = new TestUpdateEntity();
        testUpdateEntity.setId("1");
        testUpdateEntity.setName("测试1");
        testUpdateEntity.setStatus(0);
        testUpdateEntity.setDescription("描述信息");
        easyQuery.insertable(testUpdateEntity).executeRows();
        return "ok";
    }

    @Mapping(value = "/testUpdate2",method = MethodType.POST)
    public String testUpdate2(@Validated TestUpdate2Rquest request){
        TestUpdateEntity testUpdateEntity = easyQuery.queryable(TestUpdateEntity.class)
                .whereById(request.getId()).firstNotNull("未找到对应的记录");
        if(!testUpdateEntity.getStatus().equals(0)){
            return "当前状态不是0";
        }
        BeanUtil.copyProperties(request,testUpdateEntity);
        testUpdateEntity.setStatus(1);
        easyQuery.updatable(testUpdateEntity).executeRows();
        return "ok";
    }
    //自动追踪差异更新 需要开启default-track: true如果没开启那么就使用`asTracking`启用追踪
    @EasyQueryTrack
    @Mapping(value = "/testUpdate3",method = MethodType.POST)
    public String testUpdate3(@Validated TestUpdate2Rquest request){
        TestUpdateEntity testUpdateEntity = easyQuery.queryable(TestUpdateEntity.class)
                //.asTracking() //如果配置文件默认选择追踪那么只需要添加 @EasyQueryTrack 注解
                .whereById(request.getId())
                .firstNotNull("未找到对应的记录");
        if(!testUpdateEntity.getStatus().equals(0)){
            return "当前状态不是0";
        }
        BeanUtil.copyProperties(request,testUpdateEntity);
        testUpdateEntity.setStatus(1);
        easyQuery.updatable(testUpdateEntity)
                //指定更新条件为主键和status字段
                .whereColumns(o->o.columnKeys().column(TestUpdateEntity::getStatus))
                .executeRows(1,"当前状态不是0");//如果更新返回的受影响函数不是1,那么就抛出错误
        return "ok";
    }
}
